<?php
/**
 * User: b179a9
 * Date: 9/28/11
 * Time: 6:06 PM
 */

namespace Managers;

class Rubrics extends BaseManager implements CrudManager
{
    protected $__table = self::TABLE;

    const TABLE = '\Catalog\Rubrics';

    protected $cacheNames = array('rubrics');

    const TIME_IN_CACHE = 600;

    /**
     * Создает новую запись.
     * @param array $values
     */
    public function create(array $values)
    {
        $entity = new \Catalog\Rubrics();
        $this->setEntityValues($entity, $values);
        $entity->setIsDel(false);
        $this->_em->persist($entity);
        $this->flush();
        return $entity;
    }

    /**
     * Обновляет запись.
     * @param array $values
     */
    public function update(array $values)
    {
        $entity = $this->find($values['id']);
        $this->setEntityValues($entity, $values);
        $this->_em->persist($entity);
        $this->flush();
        return $entity;
    }

    protected function setEntityValues(\Catalog\Rubrics $entitiy, array $values)
    {
        $entitiy->setName($values['name']);
    }

    /**
     * Возвращает елемент по ID, false - если елемент не найден.
     *
     * @param array|bool $id
     */
    public function getById($id)
    {
        $qb = $this->createQueryBuilder()
            ->andWhere('r.id = :id')->setParameter('id', $id);
        $res = $qb->getQuery()->getArrayResult();
        return count($res) ? $res[0] : false;
    }

    protected function createQueryBuilder()
    {
        $qb = $this->_em->createQueryBuilder()
            ->select('r')
            ->from($this->__table, 'r')
            ->andWhere('r.isDel = 0');
        return $qb;
    }

    public function getList()
    {
        $cacheName = $this->cacheNames[0];
        $res = $this->_getCacheManager()->load($cacheName);
        if (!$res) {
            $qb = $this->createQueryBuilder()
                ->addOrderBy('r.id', 'DESC');
            $res = $qb->getQuery()->getArrayResult();
            $this->_getCacheManager()->save($res, $cacheName, array(), self::TIME_IN_CACHE);
        }
        return $res;
    }

    public function getSelectList()
    {
        $rubrics = $this->getList();
        $elements = array();
        foreach ($rubrics as $rubric) {
            $elements[] = new SelectElement($rubric['id'], $rubric['name']);
        }
        return $elements;
    }
}
